package humanMirror.controller.actions;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import humanMirror.model.controller.Controller;
import humanMirror.model.human.Human;


public class RegisterAction implements Action{

	public String perform(HttpServletRequest request,
			HttpServletResponse response) {

		String login = request.getParameter("login");
		String password = request.getParameter("password");

		Statement stmt = null;
		Connection conn = null;
		ResultSet r =null;
		PreparedStatement pstmt = null;

		Pattern p = Pattern.compile("[a-zA-Z0-9]+");
		Matcher loginMatcher = p.matcher(login);
		Matcher passwordMatcher = p.matcher(password);

		if (!loginMatcher.matches() || !passwordMatcher.matches()){
			request.setAttribute("errorMessage", "forbiden symbols in login/password ");
			return "/error.jsp";
		}

		try{
			Class.forName("org.sqlite.JDBC");
			conn = DriverManager.getConnection("jdbc:sqlite:c:\\HM.sqlite");

			stmt = conn.createStatement();

			stmt.execute("SELECT * FROM USERS WHERE LOGIN='" + login + "'");
			r = stmt.getResultSet();
			if (r.next()){
				request.setAttribute("errorMessage", "User with this login already exist");
				return "/error.jsp";
			} else {
				pstmt = conn.prepareStatement("INSERT INTO Users (Login,Password) VALUES (?1,?2)");
				pstmt.setString(1, login);
				pstmt.setString(2, password);
				pstmt.execute();

				HttpSession session = request.getSession(true);
				session.setAttribute("user", login);
				session.setAttribute("controller", new Controller(new Human()));
				session.setAttribute("questionNumber", 0);

				return "/main.jsp";	
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}		
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}//finally
		return null;
	}//perform

}
